package com.student.foodAfter.common.aop;

import com.student.foodAfter.entity.Userlog;
import com.student.foodAfter.service.UserlogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.Date;

/**
 * ClassName: OperLogAspect <br/>
 * Description: <br/>
 * date: 2023/1/16 10:39<br/>
 * @author 李林雨 <br/>
 * @since JDK 8
 */
@Aspect
@Component
public class OperLogAspect {
    @Pointcut("@annotation(com.student.foodAfter.common.aop.OperLog)")
    public void operLogPoinCut() {
    }
    @Resource
    private UserlogService userlogService;

    @AfterReturning(value = "operLogPoinCut()", returning="returnValue")
    public void saveOperLog(JoinPoint joinPoint, Object returnValue) throws UnsupportedEncodingException {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        OperLog opLog = method.getAnnotation(OperLog.class);
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
//        String username1 = request.getHeader("username");
//        String username = (String)request.getSession().getAttribute("username");
        String username1 = request.getHeader("loginuser");
        if(username1==null)
            username1="管理员";
        String username = URLDecoder.decode(username1, "UTF-8");
        if(username==null)
            username="管理员";
//        System.out.println("打印切面"+username);

        Date date=new Date();
        String logdate = date.toString();

        Userlog userlog = new Userlog();

        userlog.setUsername(username);
        userlog.setModule(opLog.operModul());
        userlog.setType(opLog.operType());
        userlog.setDetail(opLog.operDesc());
        userlog.setDate(logdate);
        userlogService.addUserLog(userlog);
    }
}
